<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>商品添加</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
            <el-alert title="添加商品信息" type="info" center show-icon :closable="false"></el-alert>
            <el-steps :space="200" :active="activeIndex - 0" align-center>
                <el-step title="基本信息"></el-step>
                <el-step title="商品参数"></el-step>
                <el-step title="商品属性"></el-step>
                <el-step title="商品图片"></el-step>
                <el-step title="商品内容"></el-step>
                <el-step title="完成"></el-step>
            </el-steps>
            <el-form
                :model="goodsForm"
                :rules="goodsFormRules"
                ref="goodsFormRef"
                label-width="100px"
                label-position="top"
            >
                <el-tabs
                    v-model="activeIndex"
                    :tab-position="tabPosition"
                    :before-leave="tabBeforeLeave"
                    @tab-click="tabClick"
                >
                    <el-tab-pane label="基本信息" name="0">
                        <el-form-item label="商品名称" prop="goods_name">
                            <el-input v-model="goodsForm.goods_name"></el-input>
                        </el-form-item>
                        <el-form-item label="商品价格" prop="goods_price">
                            <el-input v-model="goodsForm.goods_price" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品数量" prop="goods_number">
                            <el-input v-model="goodsForm.goods_number" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品重量" prop="goods_weight">
                            <el-input v-model="goodsForm.goods_weight" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品分类" prop="goods_cat">
                            <el-input
                                v-model="goodsForm.cat_name"
                                v-if="goodsForm.goods_id > 0"
                                :disabled="true"
                            ></el-input>
                            <el-cascader
                                v-model="goodsForm.goods_cat"
                                :options="cateList"
                                :props="cateProps"
                                @change="cateSelectChange"
                                clearable
                                v-else
                            ></el-cascader>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品参数" name="1">
                        <el-form-item
                            v-for="item in manyParamsData"
                            :label="item.attr_name"
                            :key="item.attr_id"
                        >
                            <el-checkbox-group v-model="item.attr_vals">
                                <el-checkbox
                                    v-for="(list, i) in item.attr_vals"
                                    :key="i"
                                    :label="list"
                                    border
                                ></el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品属性" name="2">
                        <el-form-item
                            v-for="item in onlyParamsData"
                            :label="item.attr_name"
                            :key="item.attr_id"
                        >
                            <el-input v-model="item.attr_vals"></el-input>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品图片" name="3">
                        <el-upload
                            :action="uploadURL"
                            :on-preview="handlePreview"
                            :on-remove="handleRemove"
                            :file-list="fileList"
                            list-type="picture"
                            :headers="uploadHeaders"
                            :on-success="handleSuccess"
                        >
                            <el-button size="small" type="primary">点击上传</el-button>
                            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                        </el-upload>
                    </el-tab-pane>
                    <el-tab-pane label="商品内容" name="4">
                        <quill-editor v-model="goodsForm.goods_introduce"></quill-editor>
                        <el-button
                            type="primary"
                            class="btn-add"
                            @click="saveGoods"
                        >{{ saveBtnName }}</el-button>
                    </el-tab-pane>
                </el-tabs>
            </el-form>
        </el-card>
        <!-- 图片预览窗口 -->
        <el-dialog title="图片预览" :visible.sync="previewDialogVisible" width="30%">
            <div class="preview-box">
                <img :src="previewPath" alt />
            </div>
        </el-dialog>
    </div>
</template>

<script>
import _ from 'lodash'
export default {
    data() {
        return {
            activeIndex: 0,
            tabPosition: 'left',
            goodsForm: {
                goods_id: 0,
                goods_name: '',
                goods_price: 0,
                goods_number: 0,
                goods_weight: 0,
                goods_cat: [],
                pics: [],
                goods_introduce: '',
                attrs: []
            },
            goodsFormRules: {
                goods_name: [
                    { required: true, message: '请输入商品名称', trigger: 'blur' }
                ],
                goods_price: [
                    { required: true, message: '请输入商品价格', trigger: 'blur' }
                ],
                goods_number: [
                    { required: true, message: '请输入商品数量', trigger: 'blur' }
                ],
                goods_weight: [
                    { required: true, message: '请输入商品重量', trigger: 'blur' }
                ],
                goods_cat: [
                    { required: true, message: '请选择商品分类', trigger: 'blur' }
                ]
            },
            cateList: [],
            cateProps: {
                expandTrigger: 'hover',
                value: 'cat_id',
                label: 'cat_name',
                children: 'children'
            },
            manyParamsData: [],
            onlyParamsData: [],
            uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
            uploadHeaders: {
                Authorization: window.sessionStorage.getItem('token')
            },
            previewPath: '',
            previewDialogVisible: false,
            saveBtnName: '',
            fileList: []
        }
    },
    created() {
        this.getCateList()
    },
    methods: {
        // 数据列表
        async getCateList() {
            this.saveBtnName = '保存商品'
            this.goodsForm.goods_id = this.$route.query.goods_id
            if (this.goodsForm.goods_id > 0) {
                const { data: res } = await this.$http.get('goods/' + this.goodsForm.goods_id)
                if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
                const { data: resCate } = await this.$http.get('categories/' + res.data.cat_id)
                if (resCate.meta.status !== 200) return this.$message.error(resCate.meta.msg)
                res.data.cat_name = resCate.data.cat_name
                res.data.pics.forEach(item => {
                    const fileObj = { name: item.pics_sma, url: item.pics_sma_url }
                    this.fileList.push(fileObj)
                })
                this.goodsForm = res.data
            } else {
                this.saveBtnName = '添加商品'
                const { data: res } = await this.$http.get('categories')
                if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
                this.cateList = res.data
            }
        },
        // cascader选择项
        cateSelectChange() {
            if (this.goodsForm.goods_cat.length !== 3) {
                this.goodsForm.goods_cat = []
            }
        },
        // tab标签切换之前的钩子
        tabBeforeLeave(activeName, oldActiveName) {
            if (this.goodsForm.goods_id > 0) {
                return true
            } else if (oldActiveName === '0' && this.goodsForm.goods_cat.length !== 3) {
                this.$message.error('请先选择商品分类!')
                return false
            }
        },
        // tab标签选中时事件
        async tabClick() {
            if (this.activeIndex === '1') {
                if (this.goodsForm.goods_id > 0) {
                    if (this.manyParamsData.length === 0) {
                        sortKey(this.goodsForm.attrs, 'attr_id')
                        this.goodsForm.attrs.forEach(item => {
                            if (item.attr_sel === 'many') {
                                item.attr_vals = item.attr_vals.split(' ')
                                this.manyParamsData.push(item)
                            }
                        })
                    }
                } else {
                    const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
                        params: { sel: 'many' }
                    })
                    if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
                    res.data.forEach(item => {
                        item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
                    })
                    this.manyParamsData = res.data
                }
            } else if (this.activeIndex === '2') {
                if (this.goodsForm.goods_id > 0) {
                    this.onlyParamsData = []
                    sortKey(this.goodsForm.attrs, 'attr_id')
                    this.goodsForm.attrs.forEach(item => {
                        if (item.attr_sel === 'only') {
                            this.onlyParamsData.push(item)
                        }
                    })
                } else {
                    const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
                        params: { sel: 'only' }
                    })
                    if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
                    this.onlyParamsData = res.data
                }
            }
        },
        // 图片上传预览
        handlePreview(file) {
            this.previewPath = file.response.data.url
            this.previewDialogVisible = true
        },
        // 图片上传移除
        handleRemove(file) {
            // 取得删除图片的临时路径
            const filePath = file.response.data.tmp_path
            // 取得pics里删除图片的索引值
            const i = this.goodsForm.pics.findIndex(item => item.pic === filePath)
            // 调用splice从pics数组中移除
            this.goodsForm.pics.splice(i, 1)
        },
        // 监听图片上传成功, response参数是指服务器返回的内容
        handleSuccess(response) {
            // 拼接得到上传图片信息对象
            const upfileObj = { pic: response.data.tmp_path }
            // 将上传图片信息push到pics数组中
            this.goodsForm.pics.push(upfileObj)
        },
        // 保存商品
        saveGoods() {
            this.$refs.goodsFormRef.validate(async valid => {
                if (!valid) return this.$message.error('请完善必填项!')
                // 用lodash插件 深克隆对象
                const gForm = _.cloneDeep(this.goodsForm)
                // 将对象转换为字符串
                if (this.goodsForm.goods_id > 0) {
                    this.goodsForm.attrs = []
                } else {
                    gForm.goods_cat = gForm.goods_cat.join(',')
                }
                this.manyParamsData.forEach(item => {
                    const paramsObj = { attr_id: item.attr_id, attr_value: item.attr_vals.join(' ') }
                    this.goodsForm.attrs.push(paramsObj)
                })
                this.onlyParamsData.forEach(item => {
                    const paramsObj = { attr_id: item.attr_id, attr_value: item.attr_vals }
                    this.goodsForm.attrs.push(paramsObj)
                })
                gForm.attrs = this.goodsForm.attrs
                if (this.goodsForm.goods_id > 0) {
                    const { data: res } = await this.$http.put('goods/' + this.goodsForm.goods_id, gForm)
                    if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
                    this.$message.success('修改商品成功!')
                } else {
                    const { data: res } = await this.$http.post('goods', gForm)
                    if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
                    this.$message.success(res.meta.msg)
                }
                this.$router.push('/goods')
            })
        }
    },
    computed: {
        cateId() {
            if (this.goodsForm.goods_id > 0) {
                return this.goodsForm.cat_id
            } else if (this.goodsForm.goods_cat.length === 3) {
                return this.goodsForm.goods_cat[2]
            }
            return null
        }
    }

}
function sortKey(array, key) {
    return array.sort(function (a, b) {
        var x = a[key];
        var y = b[key];
        return ((x < y) ? -1 : (x > y) ? 1 : 0)
    })
}
</script>

<style lang="less" scoped>
.el-steps {
    margin: @default-margin 0;
}
.el-checkbox {
    margin: 0 10px 0 0 !important;
}
.preview-box {
    text-align: center;
    img {
        max-width: 100%;
    }
}
.btn-add {
    margin-top: @default-margin;
}
</style>